import { Context, Schema, h } from 'koishi'
import { promises as fs } from 'fs'
import path from 'path'
import { image } from '@satorijs/element/jsx-runtime'


export const name = 'maobing'

// export interface Config {}
// export const Config: Schema<Config> = Schema.object({})

function makePresets(names: string[]) {
  return names.map(name => ({
    keyword: name,
    path: `${__dirname}/../assets/${name}.jpg`,
    source: "file" as const,
  }))
}

export const Config = Schema.intersect([

  Schema.object({
    presetList: Schema.array( 
      Schema.object({
        keyword: Schema.string()
          .role('textarea', { rows: [2, 4] }),
        path: Schema.string()
          .role('link'),
        source: Schema.union(['file', 'url'])
          .role(''), 
      }).role('table')
    ).role('table')
      .default(makePresets(["猫包", "猫塔", "猫柱", "猫饼", "猫粒"]))
  }).description('基础配置')


])

export function apply(ctx: Context, config) {

  ctx.on('message', async (session) => {
    // if ( session.userId != session.bot.selfId ){
    //   await session.send(`session.content = \n\t${session.content}`);    
    // }
    // ctx.logger.info(config)
    // if ( session.content.includes("foo") ){
    //   await session.send("bar");
    // }
    for ( const o of config.presetList ){
      // ctx.logger.info(`keyword = ${o.keyword}`);
      if ( session.content.includes(o.keyword) ){
        // await session.send(o.keyword);
        const imageBase64 = (await fs.readFile(o.path)).toString('base64');
        // await session.send( h.quote(session.messageId) + h.image(`data:image/png;base64,${imageBase64}`) );
        let imageMsgList = [];
        imageMsgList.push(h.quote(session.messageId));
        imageMsgList.push(h.image(`data:image/png;base64,${imageBase64}`))
        await session.send(imageMsgList);
        break;
      }
    }
  })

}
